//即使聊天 需要用到select
#include<func.h>
#include<string.h>
int main(int argc,char*argv[])
{
    // ./server1 192.168.213.128 1260
    ARGS_CHECK(argc,3);
    int sockfd = socket(AF_INET,SOCK_STREAM,0); //0是默认 返回值是sockfd文件描述符
    //准备好结构体地址
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[2]));
    //ip地址
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    //解决bind问题
    int flag = 1;//给参数分配内存 1是忽略，0 是不忽略
    int ret = setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&flag,sizeof(flag));
    ret = bind(sockfd,(struct sockaddr*)&addr,sizeof(addr)); // ret 返回值是检查是否正确
    ERROR_CHECK(ret,-1,"bind");
    //listen
    listen(sockfd,10);//半连接队列和全连接队列 10是半连接队列的长度
    //accept
    //客户端的addr
    struct sockaddr_in client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
    int netfd = accept(sockfd,(struct sockaddr*)&client_addr,&client_addr_len);
    fd_set rdset;
    char buf[4096]={0};
    while(1)
    {
        bzero(buf,sizeof(buf));
        FD_ZERO(&rdset); //初始化
        //设置
        FD_SET(STDIN_FILENO,&rdset);
        FD_SET(netfd,&rdset);
        select(netfd+1,&rdset,NULL,NULL,NULL); //后三个参数有点忘记了
        if(FD_ISSET(netfd,&rdset))
        {
            //客户端发消息
            ssize_t sret = recv(netfd,buf,sizeof(buf),0);
            //如果对面停止 按下ctrl + d
            if(sret == 0)
            {
                printf("hehe \n");
                break;
            }
            printf("sret = %ld,buf = %s\n",sret,buf);
        }
        if(FD_ISSET(STDIN_FILENO,&rdset))
        {
            //服务端发消息
            ssize_t sret = read(STDIN_FILENO,buf,sizeof(buf));
            //如果自己停止
            if(sret == 0)
            {
                printf("baibai~\n");
                break;
            }
            send(netfd,buf,sret,0);
        }
    }
    close(netfd);
    close(sockfd);
}